#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#      This file is distributed as part of the WebAMP2 project and is licensed
#      under the GPL version 3.
#
#      Copyright 2007 Chris Seickel <cseickel@gmail.com>
#
#      This program is free software; you can redistribute it and/or modify
#      it under the terms of the GNU General Public License version 3 as 
#      published by the Free Software Foundation.
#
#      This program is distributed in the hope that it will be useful,
#      but WITHOUT ANY WARRANTY; without even the implied warranty of
#      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#      GNU General Public License version 3 for more details.
#
#      You should have received a copy of the GNU General Public License
#      along with this program; if not, write to:
#       Free Software Foundation, Inc.
#       51 Franklin Street, Fifth Floor
#       Boston, MA 02110-1301, USA


from functools import partial

class ObservedVar:
    def __init__(self, id, value):
        self.__dict__["changed"] = [self.changed]
        self.id = id
        self.__dict__["value"] = None
        self.value = value
            
    def connect(self, f):
        self.__dict__["changed"].append(f)
    
    def changed(self, value):
        try:
            print self.id, "changed to", str(value)
        except TypeError:
            print self.id, "changed to <TypeError>"
        
    def __setattr__(self, name, value):
        if name == "value":
            if value <> self.__dict__["value"]:
                for f in self.changed:
                    f(value)
        self.__dict__[name] = value
                
        
class ObservedPlaylist:
    def __init__(self):
        self.items = []
        self.version = 0
        self.time = 0
        self.verChanged = [self.changed]
                
    def connect(self, f):
        self.verChanged.append(f)
    
    def changed(self, ver):
        print "Playlist changed."
        
    def __setattr__(self, name, value):
        if name == "version":
            if self.__dict__.has_key("version"):
                if self.version <> value:
                    t = 0
                    for tm in self.times:
                        t += int(tm)
                    self.time = t
                    for f in self.verChanged:
                        f(value)
        self.__dict__[name] = value
            
        
obs_curSong = ObservedVar("curSongPLID", None)
obs_elapsedTime = ObservedVar("elapsedTime", 0)
obs_totalTime = ObservedVar("totalTime", 0)
obs_state = ObservedVar("state", "stop")
obs_volume = ObservedVar("volume", 0)
obs_random = ObservedVar("random", 0)
obs_repeat = ObservedVar("repeat", 0)
obs_dbUpdating = ObservedVar("dbUpdating", False)
obs_dbStats = ObservedVar("dbStats", None)
obs_playlist = ObservedPlaylist()
    
    